<?php

namespace App\Http\Controllers;

use App\Exceptions\ApiException;
use App\Http\Resources\FactoryCollection;
use App\Models\Factory;
use App\Models\FactoryLike;
use App\Models\User;
use App\Models\VerifyCode;

use App\Models\UserLogin;
use Illuminate\Http\Request;
use Overtrue\LaravelWeChat\EasyWeChat;

class AuthController extends Controller
{
    public function loginCode(Request $request)
    {
        $code = $request->input('code');
        $easyWechat = EasyWeChat::miniApp();
        try {
            $app = $easyWechat->getUtils()->codeToSession($code);
        } catch (\Exception $exception) {
            return response()->json([
                'code' => 201,
                'message' => $exception->getMessage(),
            ]);
        }
        if (!isset($app['openid'])) {
            throw new ApiException(json_encode($app));
        }
        $userLogin = UserLogin::where('openid', $app['openid'])->where('type', 1)->first();
        if (!$userLogin) {
            $userLogin = new UserLogin();
            $userLogin->type = 1;
            $userLogin->openid = $app['openid'];
            $userLogin->session_key = $app['session_key'];
            $userLogin->save();
        } else {
            $userLogin->session_key = $app['session_key'];
            $userLogin->save();
        }
        return response()->json([
            'code' => 200,
            'msg' => 'success',
            'data' => $userLogin
        ]);
    }

    /**
     * @return void
     */
    public function  loginByPhone(Request  $request){
        $openid=$request->input('openid');
        $data = $request->all();
        $userLogin=  UserLogin::where('openid',$openid)->first();
        $user = User::where('mobile', $data['mobile'])->first();
        if (!$user) {
            $user = new User();
            $user->mobile = $data['mobile'];
            $user->password = bcrypt('123456');
            $user->save();
            $user->name=$user->id.'用户';
            $user->save();
        }

        $verifyCode = VerifyCode::where('account', $data['mobile'])->first();
        if ($verifyCode) {
            $time = $verifyCode->updated_at ?? $verifyCode->created_at;
            if ($data['code'] != $verifyCode->verify_code_num) {
                throw  new ApiException('验证码不正确');
            }
            if (strtotime(now()) - strtotime($time) > 600) {
                throw new ApiException('验证码已过期');
            }
        }else{
            throw new ApiException('请输入验证码');
        }
        if (!$userLogin){
            $userLogin=new UserLogin();
            $userLogin->openid=$openid;
            $userLogin->user_id=$user->id;
            $userLogin->type=1;
            $userLogin->save();
        }else if (!$userLogin->user_id){
            $userLogin->user_id=$user->id;
            $userLogin->save();
        }
        $token = $user->createToken('token')->plainTextToken;
        return response()->json(
            [
                'code' => 200,
                'data' => [
                    'user'=>$user->toArray(),'token'=>$token
                ]
            ]
        );
    }
    /**
     * @return void
     */
    public function loginByWechat(Request  $request){
        $code = $request->input('code');
        $openid=$request->input('openid');
        $userLogin=UserLogin::whereOpenid($openid)->first();
        if (!$userLogin){
            throw new ApiException('没有openid');
        }
        $easyWechat = EasyWeChat::miniApp();
        $api = $easyWechat->getClient();
        $response = $api->post('/wxa/business/getuserphonenumber', [
            'json' => ['code' => $code]
        ]);
        $data=$response->toArray();
        if (isset($data['errcode'])&&$data['errcode']==0){
            $mobile=$data['phone_info']['phoneNumber'];
            if (!$userLogin->user_id){
                $user = User::where('mobile', $mobile)->first();
                if (!$user) {
                    $user = new User();
                    $user->mobile =$mobile;
                    $user->password = bcrypt('123456');
                    $user->save();
                    $user->name=$user->id.'用户';
                    $user->save();
                }
                $userLogin->user_id = $user->id;
                $userLogin->save();
            }else{
                $user = User::find($userLogin->user_id);
            }
            $token = $user->createToken('token')->plainTextToken;
            return response()->json([
                'code' => 200,
                'message' => '成功',
                'data' => ['user'=>$user->toArray(),'token'=>$token]
            ]);
        }else{
            throw new ApiException('服务器错误');
        }
    }

    public function getPhoneNumber(Request $request)
    {
        $code = $request->input('code');

        $easyWechat = EasyWeChat::miniApp();
        $api = $easyWechat->getClient();
        $response = $api->post('/wxa/business/getuserphonenumber', [
            'json' => ['code' => $code]
        ]);

        return $response->toArray();
    }

    public function loginByPassword(Request $request)
    {
        $userName = $request->input('username');
        $password = $request->input('password');

        $user = User::where('name', $userName)->first();
        return response()->json([
            'code' => 200,
            'msg' => 'success',
            'data' => $user->createToken('token')->plainTextToken
        ]);
    }

    public function  releaseList(Request  $request){
        $user=$request->user();
        $type=$request->input('type');
        $pageSize=$request->input('page_size');
        $factory=Factory::where('user_id',$user->id)
            ->when($type,function ($query)use ($type){
                $query->where('type',$type);
            })
            ->orderBy('id','desc')
            ->paginate($pageSize);
        return new FactoryCollection($factory);
    }

}
